'use client'
import {
   MenuFoldOutlined,
   HomeOutlined,
   PoweroffOutlined,
   MenuUnfoldOutlined,
   FileOutlined,
   DownOutlined,
   UserOutlined,
   BookOutlined,
   QuestionCircleOutlined
} from '@ant-design/icons';
import zhCN from 'antd/es/locale/zh_CN';
import {
   Layout, Menu, Dropdown, MenuProps, Button, message, Popconfirm, Form,
   Input, Radio, Table, Select, Tag, Modal,ConfigProvider
} from 'antd';
import type { TableColumnsType, PopconfirmProps } from 'antd';
import React, { useState, ChangeEvent, useEffect, useRef } from 'react';
import { useRouter } from 'next/navigation'
import type { DraggableData, DraggableEvent } from 'react-draggable';
import Draggable from 'react-draggable';
import type { TableProps } from 'antd';
import type { PaginationProps } from 'antd';
import Link from 'next/link';
import { getCookie } from '../utils'
interface favType {
   ttid: number,
   ttname: string
}
type FieldType = {
   toname: string;
   toabbreviation: string;
   tolelvel1?: string;
   tolelvel2?: string;
   tolelvel3?: string;
   tolelvel4?: string;
   tolelvel5?: string;
   tostatus: number;
   todescription?: string;

};
interface DataType {
   toid: number,
   tofrom: string;
   tohref: string;
   tolink: string;
   toname: string,
   totime: string;
}
interface DataType {
   toid: number,
   toname: string;
   toabbreviation: string;
   todataNumber: number;
   tomodifytime: string,
   tocreatetime: string;
   tolelvel1: string,
   tolelvel2: string,
   tolelvel3: string,
   tolelvel4: string,
   tolelvel5: string,
   tostatus: string,
   todescription: string
}
const { Header, Sider, Content } = Layout;
const { TextArea } = Input;

const DocMgt: React.FC = () => {
   const [collapsed, setCollapsed] = useState(false);
   const useStateRef = useRef('')

   const [username, setUsername] = useState('');
   const [isModalOpen, setIsModalOpen] = useState(false);
   const [disabled, setDisabled] = useState(true);
   const draggleRef = useRef<HTMLDivElement>(null);
   const [iputVal, setIputVal] = useState('');
   const [tags, setTags] = useState<string[]>(['Tag1']);
   const [form] = Form.useForm();
   const showTotal: PaginationProps['showTotal'] = (total) => `一共 ${total} 条`;

   const [pagination, setPagination] = useState({
      current: 1,
      pageSize: 10,
      total: 1,
      showTotal,
      showSizeChanger: true
   })

   const [bounds, setBounds] = useState({ left: 0, top: 0, bottom: 0, right: 0 });
   const onStart = (_event: DraggableEvent, uiData: DraggableData) => {
      const { clientWidth, clientHeight } = window.document.documentElement;
      const targetRect = draggleRef.current?.getBoundingClientRect();
      if (!targetRect) {
         return;
      }
      setBounds({
         left: -targetRect.left + uiData.x,
         right: clientWidth - (targetRect.right - uiData.x),
         top: -targetRect.top + uiData.y,
         bottom: clientHeight - (targetRect.bottom - uiData.y),
      });
   };

   const changeInputVal = (event: ChangeEvent<HTMLInputElement>) => {
      setIputVal(event.target.value);
   };
   const handleDelete = (id: number) => {
      fetch('/SWJDTXT/deleteTownds.action?toid=' + id, { method: 'POST' }).then(res => {
         res.text().then(datas => {
            if (datas == '成功') {
               message.success('删除成功');
               // fetchTableData(selectedValue.split('-')[1])
            } else {
               message.error('删除失败！')
            }
         })
      })
   };
   const columns: TableColumnsType<DataType> = [
      {
         title: '数据集名称',
         dataIndex: 'toname',
         key: 'toname',
         width: 200,
         fixed: 'left',
      },
      {
         title: '缩写',
         width: 80,
         dataIndex: 'toabbreviation',
         key: 'toabbreviation'
      },
      {
         title: '数据创建时间',
         dataIndex: 'tocreatetime',
         key: 'totime',
         width: 120,
      },
      {
         title: '等级1',
         dataIndex: 'tolelvel1',
         key: 'tolelvel1',
         width: 70,
      },
      {
         title: '等级2',
         dataIndex: 'tolelvel2',
         key: 'tolelvel2',
         width: 70,
      },
      {
         title: '等级3',
         dataIndex: 'tolelvel3',
         key: 'tolelvel3',
         width: 70,
      },

      {
         title: '等级4',
         dataIndex: 'tolelvel4',
         key: 'tolelvel4',
         width: 70,
      },
      {
         title: '等级5',
         dataIndex: 'tolelvel5',
         key: 'tolelvel5',
         width: 70,
      },
      {
         title: '状态',
         dataIndex: 'tostatus',
         key: 'tostatus',
         width: 90,
         render: (_, record) => <div>
            {record.tostatus == '1' ? '已添加' : '未添加'}
         </div>
      },
      {
         title: '简介',
         dataIndex: 'todescription',
         key: 'todescription',
         width: 280,
      },
      {
         title: '操作',
         key: 'operation',
         fixed: 'right',
         width: 100,
         render: (_, record) => <Popconfirm
            title="温馨提示"
            description="你确定要删除这个数据集吗?"
            onConfirm={() => handleDelete(record.toid)}
            okText="确定"
            cancelText="取消"
         >
            <Button type='primary' danger>删除</Button>
         </Popconfirm>,
      },
   ];
   const [data, setData] = useState<DataType[]>();
   useEffect(() => {
      let username = getCookie('sjhm');
      setUsername(() => {
         useStateRef.current = username;
         return useStateRef.current
      });
      queryData();
      return () => {
         // 组件即将卸载，这里可以做一些清理工作，如取消请求等
      };
   }, []);
   const queryData = (currentPage?: number,pageSizes?:number) => {
      let currentPages = currentPage ? currentPage : pagination.current;
      let pageSize = pageSizes?pageSizes:pagination.pageSize;
      fetch(`/SWJDTXT/queryTomandsk?topage=${currentPages}&toman=${useStateRef.current}&topagesize=${pageSize}&toname=${iputVal}`, { method: 'POST' }).then(res => {
         let resultData = res.json()
         resultData.then(results => {
            if (results instanceof Array && results.length > 0) {
               let data = results[0].data;
               let total = results[0].total;
               setPagination({ total: total, current: currentPages, pageSize: pageSize, showTotal, showSizeChanger: true })
               setData(data)
            }
         })
      })
   }
   const handleTableChange = (pagination: TableProps<DataType>['pagination']) => {
      if (pagination) {
         setPagination({ total: pagination.total ? pagination.total : 0, current: pagination.current ? pagination.current : 1, pageSize: pagination.pageSize ? pagination.pageSize : 10, showTotal, showSizeChanger: true })
      }
      if (pagination && pagination.current&& pagination.pageSize) {
         queryData(pagination.current,pagination.pageSize)
      }
   }
   const handleClose = (tag: string) => {
      console.log(tag)
      // const newTags = tags.filter((tag) => tag !== removedTag);
      // console.log(newTags);
      // setTags(newTags);
   };

   const addData = () => {
      setIsModalOpen(true);
   }
   const router = useRouter()
   function onClick(obj: { key: string }) {
      if (obj.key === '1') {
         // 跳转到官网
      } else {
         // 退出登录
      }
   };
   const onClickMenu: MenuProps['onClick'] = e => {
      if (e.key == '11') {
         // 跳转到用户信息-我的信息页面
         router.push('/user')
      } else if (e.key == '31') {
         // 跳转到自定义数据集-数据集社区页面
         router.push('/dataClub')
      } else if (e.key == '32') {
         // 跳转到自定义数据集-已选数据集页面
         router.push('/dataChosen')
      } else if (e.key == '2') {
         // 跳转到自定义数据集-已选数据集页面
         router.push('/paperMgt')
      }
   };
   const items = [{
      key: '1',
      label: (
         <Link href="https://www.xsjxkt.com">
            <HomeOutlined /><span style={{ marginLeft: 6 }}>回到官网</span>
         </Link>
      ),
   }, {
      key: '2',
      label: (
         <div><PoweroffOutlined /><span style={{ marginLeft: 6 }}>退出登录</span></div>
      ),
   }]
   const handleOk = () => {
      setIsModalOpen(false);
   };

   const handleCancel = () => {
      setIsModalOpen(false);
   };
   const confrimAdd = () => {
      form
         .validateFields({
            validateOnly: true,
         })
         .then(() => {
            const fromData = form.getFieldsValue() as FieldType;
            fetch(`/SWJDTXT/saveTownds.action?todataNumber=0&toman=${username}&toname=${fromData.toname}&toabbreviation=${fromData.toabbreviation}&tolelvel1=${fromData.tolelvel1 ? fromData.tolelvel1 : ''}&tolelvel2=${fromData.tolelvel2 ? fromData.tolelvel2 : ''}&tolelvel3=${fromData.tolelvel3 ? fromData.tolelvel3 : ''}&tolelvel4=${fromData.tolelvel4 ? fromData.tolelvel4 : ''}&tolelvel5=${fromData.tolelvel5 ? fromData.tolelvel5 : ''}&tostatus=${fromData.tostatus}&todescription=${fromData.todescription}`, { method: 'POST' }).then(res => {
               res.text().then(datas => {
                  if (datas == '成功') {
                     handleCancel();
                     message.success('添加成功！');
                     queryData()
                  }
               })
            })
         })
         .catch(() => { });
   }
   return (
      <Layout style={{ height: '100%' }}>
         <Sider style={{ backgroundColor: '#f5f5f5' }} trigger={null} collapsible collapsed={collapsed}>
            <div className="logo" />
            <Menu style={{ backgroundColor: '#f5f5f5', border: 'none' }}
               theme="light"
               onClick={onClickMenu}
               mode="inline"
               defaultOpenKeys={['3']}
               defaultSelectedKeys={['33']}
               items={[
                  {
                     key: '2',
                     icon: <BookOutlined />,
                     label: '文献管理',
                  },
                  {
                     key: '3',
                     icon: <FileOutlined />,
                     label: '自定义数据集',
                     children: [
                        {
                           key: '31',
                           label: '数据集社区',
                        },
                        {
                           key: '32',
                           label: '已选数据集',
                        },
                        {
                           key: '33',
                           label: '编辑数据集',
                        }
                     ]
                  },
               ]}
            />
         </Sider>
         <Layout className="site-layout" style={{ backgroundColor: '#fff' }}>
            <Header className="site-layout-background" style={{ backgroundColor: '#f5f5f5', paddingLeft: 12 }}>
               {React.createElement(collapsed ? MenuUnfoldOutlined : MenuFoldOutlined, {
                  className: 'trigger',
                  onClick: () => setCollapsed(!collapsed),
               })}
               <div style={{ float: 'right' }}>
                  <Dropdown menu={{ items, onClick }}>
                     <a onClick={e => e.preventDefault()}>
                        <UserOutlined /> {username}
                        <DownOutlined style={{ marginLeft: 8 }} />
                     </a>
                  </Dropdown>
               </div>
            </Header>
            <Content
               className="site-layout-background"
               style={{
                  padding: 24,
               }}
            >
               <div style={{ marginBottom: 6 }}>
               <Input style={{ display: 'inline-block', width: 240, marginLeft: 6 }} placeholder="数据集名称" value={iputVal} onChange={changeInputVal} defaultValue="" />
               <Button type="primary" style={{ margin: '0 6px' }} onClick={() => { queryData(1) }} autoInsertSpace>
                  查询
               </Button>
                  <Button type='primary' onClick={addData}>新建数据集</Button>
                  <div style={{ marginTop: 12 }}>
                     <ConfigProvider locale={zhCN}>
                        <Table
                           size="small"
                           columns={columns}
                           pagination={pagination}
                           bordered
                           onChange={handleTableChange}
                           dataSource={data}
                           rowKey={(record) => record.toid}
                           sticky={{ offsetHeader: 64 }}
                        />
                     </ConfigProvider>
                  </div>
               </div>
               <Modal title={
                  <div
                     style={{
                        width: '100%',
                        cursor: 'move',
                     }}
                     onMouseOver={() => {
                        if (disabled) {
                           setDisabled(false);
                        }
                     }}
                     onMouseOut={() => {
                        setDisabled(true);
                     }}
                     onFocus={() => { }}
                     onBlur={() => { }}
                  // end
                  >
                     新建数据集信息
                  </div>
               } footer={null} width={560} open={isModalOpen} onOk={handleOk} onCancel={handleCancel} modalRender={(modal) => (
                  <Draggable
                     disabled={disabled}
                     bounds={bounds}
                     nodeRef={draggleRef}
                     onStart={(event, uiData) => onStart(event, uiData)}
                  >
                     <div ref={draggleRef}>{modal}</div>
                  </Draggable>
               )}>
                  <div>
                     <Form form={form}
                        labelCol={{ span: 5 }}
                        wrapperCol={{ span: 17 }}
                        layout="horizontal"
                     >
                        <Form.Item<FieldType> name="toname" label="数据集名称" rules={[{ required: true, message: '请输入数据集名称' }]} >
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="toabbreviation" tooltip="缩写将出现页面的颜色块中" label="数据集缩写" rules={[{ required: true, message: '请输入数据集缩写' }]}>
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tolelvel1" label="等级一" tooltip="数据集中的数据分级不能以等级1开始，也不能以等级5结束" >
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tolelvel2" label="等级二">
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tolelvel3" label="等级三">
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tolelvel4" label="等级四">
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tolelvel5" label="等级五">
                           <Input />
                        </Form.Item>
                        <Form.Item<FieldType> name="tostatus" tooltip="系统会定期清理数据量为0的公开数据" label="分享范围" rules={[{ required: true, message: '请选择分享范围' }]}>
                           <Radio.Group>
                              <Radio value="0"> 公开 </Radio>
                              <Radio value="1"> 私有 </Radio>
                           </Radio.Group>
                        </Form.Item>
                        <Form.Item<FieldType> name="todescription" label="数据集描述" tooltip="数据集的描述" rules={[{ required: true, message: '请输入数据集描述' }, {
                           max: 100, message: '最多输入100个字符'
                        }]}>
                           <TextArea rows={4} />
                        </Form.Item>
                     </Form>
                     <div style={{ textAlign: 'center' }}> <Button type='primary' onClick={confrimAdd}>确认</Button></div>
                  </div>
               </Modal>
            </Content>
         </Layout>
      </Layout>
   );
};

export default DocMgt;